package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname OrderServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/7/5 13:49
 * @Created by Ren
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AddressBookMapper addressBookMapper;
    @Resource
    private UserEmployeeMapper userEmployeeMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Resource
    private WebSocketServer webSocketServer;

    private Orders orders_;

    /**
     * 生成订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种业务一场(地址薄,购物车数据为空)

        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //判断用户的收货地址距离商家门店是否超出配送范围(配送范围为5公里内),则下单失败。


        //构造订单表中的数据
        String address = addressBook.getProvinceName()
                + addressBook.getCityName()
                + addressBook.getDistrictName()
                + addressBook.getDetail();
        User user = userEmployeeMapper.getById(BaseContext.getCurrentId());
        Orders order = Orders.builder()
                .number(String.valueOf(System.currentTimeMillis()) + BaseContext.getCurrentId()) // 订单号
                .status(Orders.PENDING_PAYMENT)     // 订单状态: 待付款
                .userId(BaseContext.getCurrentId()) //下单用户
                .addressBookId(ordersSubmitDTO.getAddressBookId())  //地址id
                .orderTime(LocalDateTime.now())     //下单时间
                .checkoutTime(null)   //结账时间
                .payMethod(ordersSubmitDTO.getPayMethod())  //结账方式
                .payStatus(Orders.UN_PAID)  //支付状态
                .amount(ordersSubmitDTO.getAmount())  //实收金额
                .remark(ordersSubmitDTO.getRemark())  //备注
                .phone(user.getPhone())  //下单人的手机号
                .address(address)        //地址
                .userName(user.getName())  //用户名称
                .consignee(addressBook.getConsignee())  //收货人
                .cancelReason(null)  //订单取消原因
                .rejectionReason(null)  //订单拒绝原因
                .cancelTime(null)  //订单取消时间
                .estimatedDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime())  //预计送达时间
                .deliveryStatus(ordersSubmitDTO.getDeliveryStatus())  //配送状态  1立即送出  0选择具体时间
                .deliveryTime(null) //送达时间
                .packAmount(ordersSubmitDTO.getPackAmount())  //打包费
                .tablewareNumber(ordersSubmitDTO.getTablewareNumber())  //餐具数量
                .tablewareStatus(ordersSubmitDTO.getTablewareStatus())  //餐具数量状态 1按餐量提供  0选择具体数量
                .build();
        this.orders_ = order;
        orderMapper.insert(order);
        //构造订单详情表中的数据
        //得到当前用户提交订单中的购物车数据
        ArrayList<OrderDetail> orderDetailArrayList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetailArrayList.add(orderDetail);
        }
        //批量插入
        orderDetailMapper.insertBatch(orderDetailArrayList);
        //清空购物车数据
        shoppingCartMapper.clean(BaseContext.getCurrentId());
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 用户端历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(int pageNum, int pageSize, Integer status) {

        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.historyOrders(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        for (Orders orders : page) {
            Long orderId = orders.getId();// 订单id

            // 查询订单明细
            List<OrderDetail> orderDetails = orderDetailMapper.getById(orderId);

            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetails);

            list.add(orderVO);
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userEmployeeMapper.getById(userId);

/*         //调用微信支付接口，生成预支付交易单
       JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
 */
        //进行校验
        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        if (orders.getStatus() == Orders.CANCELLED) {
            log.info("异常信息：订单超时已经取消,支付失败");
            return null;
        }
        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();//更新支付时间

        orderMapper.updateStatus(OrderStatus,
                OrderPaidStatus,
                check_out_time,
                orders.getId());

        //通过websorcket向客户端浏览器推送消息 type orderId content
        HashMap hashMap = new HashMap();
        hashMap.put("type", 1);
        hashMap.put("orderId", orders.getId());
        hashMap.put("content", "订单号:" + orders.getNumber());
        String json = JSON.toJSONString(hashMap);

        webSocketServer.sendToAllClient(json);


        //没办法用微信支付,只能修改代码,后端不去调用微信服务器,前端直接重定向到支付成功页面
        return null;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

//        // 根据订单号查询订单
//        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
//
//        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED)
//                .payStatus(Orders.PAID)
//                .checkoutTime(LocalDateTime.now())
//                .build();
//
//        orderMapper.update(orders);
    }

    /**
     * 根据 订单id去查询数据
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {

        //返回订单数据
        Orders orders = orderMapper.getById(id);
        //返回订单详情数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
        //构造返回的数据
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Override
    public void cancel(Long orderId) {
        //判断当前订单状态
        Orders orders = orderMapper.getById(orderId);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        Integer status = orders.getStatus();
        //1待付款
        if (status == 1) {
            //待付款不用退款直接修改订单状态就行
            orders.setCancelTime(LocalDateTime.now());    //修改订单取消时间
            orders.setStatus(Orders.CANCELLED);           //修改订单状态
            orders.setCancelReason("用户取消订单");         //修改取消原因
            orderMapper.update(orders);
        }
        //2待接单
        if (status == 2) {
            //订单取消并返回退款
            orders.setCancelTime(LocalDateTime.now());    //修改订单取消时间
            orders.setStatus(Orders.CANCELLED);           //修改订单状态
            orders.setPayStatus(Orders.PENDING_PAYMENT);  //修改支付状态退款
            //调用退款 todo 修改订单状态,商家金额修改
            //这里可能直接去修改管理员的金额-当前订单的金额
            orderMapper.update(orders);
        }
        //3已接单
        if (status == 3) {
            //用户给商家打电话询问是否同意取消订单 同意-自动退款 不同意-派送
        }
        //4派送中
        if (status == 4) {
            //用户给商家打电话询问是否同意退款 申请退款
        }
        //5已完成
        if (status == 5) {
            //用户给商家打电话询问是否同意退款 申请退款
        }


    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param orderId
     */
    @Override
    public void repetition(Long orderId) {
        //根据订单号查询购物车里面的数据,在生成一份

        //拿到订单数据
        //Orders order = orderMapper.getById(orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(orderId);

        ArrayList<ShoppingCart> shoppingCartArrayList = new ArrayList<>();
        //复制上一单的购物车数据
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartArrayList.add(shoppingCart);
        }
        //批量插入购物车数据
        shoppingCartMapper.insertBatch(shoppingCartArrayList);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ArrayList<OrderVO> records = new ArrayList<>();
        Page<Orders> page = orderMapper.conditionSearch(ordersPageQueryDTO);


        //拿到订单找到对应的订单详情
        for (Orders orders : page) {
            List<OrderDetail> orderDetails = orderDetailMapper.getById(orders.getId());

            //构造要返回的数据订单
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            //构造订单详情数据
            StringBuffer stringBuffer = new StringBuffer("菜品" + "\n");
            for (OrderDetail orderDetail : orderDetails) {
                stringBuffer.append(orderDetail.getName() + "*" + "\n")
                        .append(orderDetail.getNumber() + "\t")
                        .append(orderDetail.getAmount());
            }
            String orderDishes = stringBuffer.toString();
            orderVO.setOrderDishes(orderDishes);

            records.add(orderVO);
        }


        return new PageResult(page.getTotal(), records);
    }

    /**
     * 根据订单号查询对应数据
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetailById(Long id) {

        Orders order = orderMapper.getById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO getOrderStatistics() {

        Integer toBeConfirmedCount = orderMapper.
                getOrderStatisticsByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmedCount = orderMapper
                .getOrderStatisticsByStatus(Orders.CONFIRMED);
        Integer deliveryInProgressCount = orderMapper
                .getOrderStatisticsByStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmedCount)
                .confirmed(confirmedCount)
                .deliveryInProgress(deliveryInProgressCount)
                .build();

        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param orderId
     */
    @Override
    public void confirm(Long orderId) {
        Orders order = orderMapper.getById(orderId);
        order.setStatus(Orders.CONFIRMED);
        orderMapper.update(order);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {

        //修改订单状态,并返回金额
        Orders order = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = order.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            //假装调用了退款方法...
            order.setPayStatus(Orders.REFUND); //修改订单支付状态 退款
        }
        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        order.setStatus(Orders.CANCELLED); //先取消订单
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason()); //设置拒单原因
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(order);
    }

    /**
     * 完成订单
     *
     * @param orderId
     */
    @Override
    public void complete(Long orderId) {
        // 根据id查询订单
        Orders order = orderMapper.getById(orderId);

        // 校验订单是否存在，并且状态为4
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 更新订单状态,状态转为完成
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 订单派送中
     *
     * @param id
     */
    @Override
    public void delivery(Long orderId) {

        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(orderId);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {

        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //通过websorcket向客户端浏览器推送消息 type orderId content
        HashMap hashMap = new HashMap();
        hashMap.put("type", 2);
        hashMap.put("orderId", orders.getId());
        hashMap.put("content", "订单号:" + orders.getNumber());
        String json = JSON.toJSONString(hashMap);
        webSocketServer.sendToAllClient(json);
    }

}
